package vtc;

import java.util.Date;
import java.util.concurrent.*;
import java.util.concurrent.*;
import java.io.File; 
import java.io.IOException;
import jxl.*;
import jxl.read.biff.*;

public class XlsGoogleDateOpenInputUnit extends InputUnit
{
	private Integer row_;
	private Workbook workbook_;
	private Sheet sheet_;
	private int delay_;

	XlsGoogleDateOpenInputUnit(String id, VtcArrayBlockingQueue outQueues[], String path, int delay)
	{
		super(id, outQueues);
		delay_ = delay;
		try
		{
			workbook_ = Workbook.getWorkbook(new File(path));
			sheet_ = workbook_.getSheet(0);
			row_ = sheet_.getRows()-1;
		}
		catch(BiffException e)
		{
			System.out.print("BiffException in XlsGoogleDateOpenPU constructor. " + e.getMessage());
		}
		catch(IOException e)
		{
			System.out.print("IOException  in XlsGoogleDateOpenPU constructor. " + e.getMessage());
		}
	}
	
	public VtcTimeTaggedEvent inputProcess() throws InterruptedException
	{
		Cell cellA;
		Cell cellB;
		try
		{
			cellA = sheet_.getCell(0,row_);
			cellB = sheet_.getCell(1,row_);
		}
		catch(ArrayIndexOutOfBoundsException e)
		{
			System.out.print("ArrayIndexOutOfBoundsExceptio during XlsGoogleDateOpenPU::preProcess(). \n" + e.getMessage());
			throw(new InterruptedException());
		}
		Date date;
		double number;
		if(cellA.getType() == CellType.DATE) 
		{ 
			DateCell dc = (DateCell) cellA; 
			date = dc.getDate();
		}
		else
		{
			date = new Date();
		}
		if (cellB.getType() == CellType.NUMBER) 
		{ 
			NumberCell nc = (NumberCell) cellB; 
			number = nc.getValue();
		}
		else
		{
			number = 0;
		}
		VtcTimeTaggedEvent event = new VtcTimeTaggedEvent(number, date);
		//System.out.print("XlsGoogleDateOpenInputUnit::inputProcess(),number: " + number + " Date: " + date + "\n");	
		row_--;
		
		try
		{
			TimeUnit.MILLISECONDS.sleep(delay_);
		}
		catch(InterruptedException e)
		{
			System.out.print("XlsGoogleDateOpenInputUnit::inputProcess()\n");
			throw e;
		}
		return event;
	}
}